package com.zzxy.spring34.factory;

import com.zzxy.spring34.aspect.MyAspect;
import com.zzxy.spring34.service.IStudentService;
import com.zzxy.spring34.service.impl.StudentServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyBeanFactoryCglib {
    public static IStudentService createStudentServiceProxy(){
        //1.targer class
        StudentServiceImpl studentService= new StudentServiceImpl();
        //2.advice
        MyAspect aspect = new MyAspect();
        //3.weaving based jdk
          Enhancer enhancer = new Enhancer();
          enhancer.setSuperclass(studentService.getClass());
          enhancer.setCallback(new MethodInterceptor() {
              @Override
              public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                  aspect.before();
                  Object obj = methodProxy.invokeSuper(o,objects);
                  aspect.after();
                  return obj;
              }
          });
        return (StudentServiceImpl) enhancer.create();
        /*IStudentService studentServiceProxy = (IStudentService) Proxy.newProxyInstance(MyBeanFactoryCglib.class.getClassLoader(), studentService.getClass().getInterfaces(), new InvocationHandler() {
           *//* @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                aspect.before();
                Object obj= method.invoke(studentService,args);
                aspect.after();
                return obj;
            }
        });

        return studentServiceProxy;*//*
            */
    }
}
